package hui.zhang.web.action.base;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.JSONObject;

import hui.zhang.crm.domain.Customer;
import hui.zhang.domain.base.FixedArea;
import hui.zhang.service.base.FixedAreaService;
import hui.zhang.utils.BaseAction;

@SuppressWarnings("serial")
@Controller
@ParentPackage("struts-default")
@Namespace("/")
@Scope("prototype")
public class FixedAreaAction extends BaseAction<FixedArea> {
	
	@Autowired
	private FixedAreaService fixedAreaService;
	
	@Action(value="fixedArea_save",results={@Result(name="success",
			type="redirect",location="/pages/base/fixed_area.html")})
	public String save() {
		fixedAreaService.save(model);
		return SUCCESS;
	}
	
	
	@Action(value="fixedArea_pageQuery")
	public String findAllByPage() {
		Pageable pageable = new PageRequest(page-1, rows);
		Specification<FixedArea> specification = new Specification<FixedArea>() {
			List<Predicate> list = new ArrayList<Predicate>();
			public Predicate toPredicate(Root<FixedArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				if(StringUtils.isNotBlank(model.getId())) {
					Predicate p1 = cb.like(root.get("id").as(String.class), "%"+model.getId()+"%");
					list.add(p1);
				}
				if(StringUtils.isNotBlank(model.getCompany())) {
					Predicate p2 = cb.like(root.get("company").as(String.class), "%"+model.getCompany()+"%");
					list.add(p2);
				}
				//分区关联查询
//				if(StringUtils.isNotBlank(model.getSubareas())) {
//					Predicate p2 = cb.like(root.get("company").as(String.class), "%"+model.getCompany()+"%");
//					list.add(p2);
//				}
				return cb.and(list.toArray(new Predicate[0]));
			}
		};
		
		Page<FixedArea> pageData = fixedAreaService.findAll(specification, pageable);
		toJsonAndResponse(pageData);
		return NONE;
	}
	
	//查询未关联定区列表
	@Action(value="fixedArea_findNoAssociationCustomers")
	public String findNoAssociationCustomers() {
		//调用webservice 使用webClient调用
		Collection<? extends Customer> collection = 
		WebClient.create("http://localhost:8081/crm_management/services/customerService/noassociationcustomers")
		.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON)
		.getCollection(Customer.class);
		
		String jsonString = JSONObject.toJSONString(collection);
		ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
		try {
			ServletActionContext.getResponse().getWriter().write(jsonString);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return NONE;
	}
	
	//查询当前已关联定区列表
	@Action(value="fixedArea_findHasAssociationCustomers")
	public String findAssociationCustomers() {
		Collection<? extends Customer> collection = 
		WebClient.create("http://localhost:8081/crm_management/services/customerService/associationfixedareacustomers/"+model.getId())
		.accept(MediaType.APPLICATION_JSON)
		.getCollection(Customer.class);
		
		String jsonString = JSONObject.toJSONString(collection);
		ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
		try {
			ServletActionContext.getResponse().getWriter().write(jsonString);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return NONE;
	}
	
	//属性封装
	private String[] customerIds;
	public void setCustomerIds(String[] customerIds) {
		this.customerIds = customerIds;
	}
	
	//关联客户到定区
	@Action(value="fixedArea_associationCustomerToFixedArea",
			results={@Result(name="success",type="redirect",location="/pages/base/fixed_area.html")})
	public String associationCustomerToFixedArea() {
		String join = StringUtils.join(customerIds,",");
		WebClient.create("http://localhost:8081/crm_management/services/customerService/associationcustomerstofixedarea"
				+ "?customerIdStr="+join+"&fixedAreaId="+model.getId()).put(null);
		return SUCCESS;
	}
	
	//属性封装
	private Integer courierId;
	private Integer takeTimeId;
	public void setCourierId(Integer courierId) {
		this.courierId = courierId;
	}
	public void setTakeTimeId(Integer takeTimeId) {
		this.takeTimeId = takeTimeId;
	}
	//关联快递员到定区
	@Action(value="fixedArea_associationCourierToFixedArea",
			results={@Result(name="success",location="/pages/base/fixed_area.html",type="redirect")})
	public String associationCourierToFixedArea() {
		//调用业务层 定区关联快递员
		fixedAreaService.associationCourierToFixedArea(model,courierId,takeTimeId);
		return SUCCESS;
	}
	
	@Action(value="fixedArea_findAll")
	public String findAll() {
		List<FixedArea> list = fixedAreaService.findAll();
		toJsonAndResponse(list);
		return NONE;
	}

}
